package com.sinszm.wx;


import com.sinszm.common.exception.ApiException;
import com.sinszm.common.util.CommonUtils;
import com.sinszm.wx.pay.support.IWXPayDomain;
import com.sinszm.wx.pay.support.WXPay;
import com.sinszm.wx.pay.support.WXPayConfig;
import com.sinszm.wx.properties.BasicWxProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

import static com.sinszm.wx.exception.WxApiError.*;

/**
 * SzmBasicWx自动配置
 *
 * @author chenjianbo
 */
@EnableConfigurationProperties({BasicWxProperties.class})
public class SzmWxAutoConfiguration {

    @Resource
    private BasicWxProperties basicWxProperties;

    /**
     * 注册微信支付
     *
     * @return 注册支付对象
     */
    @Bean
    public WXPay wxPay() {
        try {
            WXPayConfig config = payConfig();
            return StringUtils.isEmpty(basicWxProperties.getPayNotifyUrl()) ? new WXPay(config)
                    : new WXPay(config, basicWxProperties.getPayNotifyUrl());
        } catch (Exception e) {
            throw new ApiException(WX_PAY_REG_FAIL);
        }
    }

    /**
     * 组装支付配置
     *
     * @return 配置信息
     */
    private WXPayConfig payConfig() {
        return new WXPayConfig() {
            @Override
            public String getAppID() {
                return basicWxProperties.getAppId();
            }

            @Override
            public String getMchID() {
                return basicWxProperties.getMchId();
            }

            @Override
            public String getKey() {
                return basicWxProperties.getMchKey();
            }

            @Override
            public InputStream getCertStream() {
                try {
                    if (CommonUtils.isEmpty(basicWxProperties.getMchCertUri())) {
                        throw new RuntimeException("微信支付证书文件未配置");
                    }
                    File file = new File(basicWxProperties.getMchCertUri());
                    if (!file.exists() || !file.isFile()) {
                        String url = CommonUtils.getJarDir(SzmWxAutoConfiguration.class);
                        file = new File(url + basicWxProperties.getMchCertUri());
                        if (!file.exists() || !file.isFile()) {
                            throw new ApiException(WX_PAY_CERT_NULL);
                        }
                    }
                    return new FileInputStream(file);
                } catch (Exception e) {
                    CommonUtils.logger(WXPayConfig.class.getName()).warn("微信支付证书文件未配置.");
                    return null;
                }
            }

            @Override
            public IWXPayDomain getWXPayDomain() {
                return new IWXPayDomain() {
                    @Override
                    public void report(String domain, long elapsedTimeMillis, Exception ex) {
                        CommonUtils.logger("微信支付上报[" + CommonUtils.formatTime2Second(new Date()) + "]").info(
                                "访问接口域名：" + domain + " 响应时长：" + elapsedTimeMillis + "ms");
                        if (ex != null) {
                            CommonUtils.logger("微信支付上报[" + CommonUtils.formatTime2Second(new Date()) + "]").error(ex.getMessage());
                        }
                    }

                    @Override
                    public DomainInfo getDomain(WXPayConfig config) {
                        return new DomainInfo(basicWxProperties.getMchDomain(), true);
                    }
                };
            }
        };
    }

}
